import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { budgetConfigApi } from '@/apis/budgetConfig';

/**
 * 预算配置管理相关的hooks
 */
export const useBudgetConfig = () => {
  // 状态管理
  const loading = ref(false);
  const dialogVisible = ref(false);
  const dialogTitle = ref('');
  const formRef = ref(null);
  
  // 预算配置列表数据
  const budgetConfigs = ref([]);
  


  // 搜索表单
  const searchForm = reactive({
    year: new Date().getFullYear().toString(),
    departmentId: '',
    costItemId: ''
  });

  // 分页信息
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    loading: false
  });

  // 表单数据
  const formData = reactive({
    id: '',
    departmentId: '',
    costItemId: '',
    year: new Date().getFullYear().toString(),
    budgetAmount: null,
    remark: ''
  });

  // 表单验证规则
  const formRules = reactive({
    departmentId: [
      { required: true, message: '请选择部门', trigger: 'change' }
    ],
    costItemId: [
      { required: true, message: '请选择成本项目', trigger: 'change' }
    ],
    year: [
      { required: true, message: '请选择年份', trigger: 'change' }
    ],
    budgetAmount: [
      { required: true, message: '请输入预算金额', trigger: 'blur' },
      { type: 'number', min: 0.01, message: '预算金额必须大于0', trigger: 'blur' }
    ],
    remark: [
      { max: 500, message: '备注不能超过500个字符', trigger: 'blur' }
    ]
  });

  // 部门选项
  const departmentOptions = ref([]);

  // 成本项目选项
  const costItemOptions = ref([]);
  
  // 年份选项
  const yearOptions = ref([]);
  
  // 初始化年份选项（最近5年）
  const initYearOptions = () => {
    const currentYear = new Date().getFullYear();
    const options = [];
    for (let i = currentYear - 2; i <= currentYear + 2; i++) {
      options.push({
        label: i + '年',
        value: i.toString()
      });
    }
    yearOptions.value = options;
  };
  
  // 初始化部门和成本项目选项
  const initOptions = async () => {
    try {
      // 获取部门选项
      const departmentsRes = await budgetConfigApi.getDepartments();
      departmentOptions.value = (departmentsRes.data || []).map(dept => ({
        label: dept.name || dept.deptName || `部门${dept.id}`,
        value: dept.id
      }));
      
      // 获取成本项目选项
      const costItemsRes = await budgetConfigApi.getCostItems();
      costItemOptions.value = (costItemsRes.data || []).map(item => ({
        label: item.name || item.costItemName || item.itemName || `未命名项目`,
        value: item.id
      }));
    } catch (error) {
      console.error('获取选项数据失败:', error);
      // 提供空数据
      departmentOptions.value = [];
      costItemOptions.value = [];
      console.error('无法获取部门和成本项目数据，将使用空选项');
    }
  };
  
  // 获取预算配置列表
  const getBudgetConfigs = async () => {
    try {
      loading.value = true;
      pagination.loading = true;
      
      // 构建查询参数，确保类型与后端DTO匹配，并为分页参数提供默认值
      const params = {
        departmentId: searchForm.departmentId ? Number(searchForm.departmentId) : null,
        costItemId: searchForm.costItemId ? Number(searchForm.costItemId) : null,
        year: searchForm.year ? parseInt(searchForm.year) : null,
        page: pagination.currentPage || 1,
        pageSize: pagination.pageSize || 10
      };
      
      const response = await budgetConfigApi.getBudgetConfigs(params);
      const data = response.data || {};
      
      // 数据字段映射，确保前端所需字段名正确，添加空值检查
      budgetConfigs.value = (data.records || []).map(record => ({
        id: record.id,
        departmentId: record.departmentId || record.department_id,
        departmentName: record.departmentName || record.department_name || `部门${record.departmentId || record.department_id}`,
        costItemId: record.costItemId || record.cost_item_id,
        costItemName: record.costItemName || record.cost_item_name || record.name || `未命名项目`,

        year: record.year,
        budgetAmount: record.budgetAmount || record.budget_amount || 0,
        remark: record.remark || ''
      }));
      pagination.total = data.total || 0;
    } catch (error) {
      console.error('获取预算配置列表失败:', error);
      ElMessage.error('获取数据失败，请稍后重试');
      
      // 提供空数据
      budgetConfigs.value = [];
      pagination.total = 0;
    } finally {
      loading.value = false;
      pagination.loading = false;
    }
  };
  

  
  // 查看详情
  const handleView = async (row) => {
    dialogTitle.value = '查看预算配置';
    try {
      // 调用API获取详细信息
      const response = await budgetConfigApi.getBudgetConfigById(row.id);
      
      // 增强错误检查
      if (!response || !response.data) {
        throw new Error('无效的响应数据');
      }
      
      const record = response.data;
      
      // 数据字段映射转换，增加更全面的空值检查和默认值
      const departmentId = record.departmentId || record.department_id || '';
      const costItemId = record.costItemId || record.cost_item_id || '';
      const year = record.year || new Date().getFullYear();
      const budgetAmount = record.budgetAmount || record.budget_amount || 0;
      
      const formRecord = {
        id: record.id || '',
        departmentId: String(departmentId),
        costItemId: String(costItemId),
        year: String(year), // 确保年份是字符串格式
        budgetAmount: budgetAmount,
        remark: record.remark || ''
      };
      
      // 复制数据到表单
      Object.assign(formData, formRecord);
      dialogVisible.value = true;
    } catch (error) {
      console.error('获取预算配置详情失败:', error);
      ElMessage.error('获取详情失败，请稍后重试');
    }
  };
  
  // 编辑
  const handleEdit = async (row) => {
    dialogTitle.value = '编辑预算配置';
    try {
      // 调用API获取详细信息
      const response = await budgetConfigApi.getBudgetConfigById(row.id);
      
      // 增强错误检查
      if (!response || !response.data) {
        throw new Error('无效的响应数据');
      }
      
      const record = response.data;
      
      // 数据字段映射转换，增加更全面的空值检查和默认值
      const departmentId = record.departmentId || record.department_id || '';
      const costItemId = record.costItemId || record.cost_item_id || '';
      const year = record.year || new Date().getFullYear();
      const budgetAmount = record.budgetAmount || record.budget_amount || 0;
      
      const formRecord = {
        id: record.id || '',
        departmentId: String(departmentId),
        costItemId: String(costItemId),
        year: String(year), // 确保年份是字符串格式
        budgetAmount: budgetAmount,
        remark: record.remark || ''
      };
      
      // 复制数据到表单
      Object.assign(formData, formRecord);
      dialogVisible.value = true;
    } catch (error) {
      console.error('获取预算配置详情失败:', error);
      ElMessage.error('获取详情失败，请稍后重试');
    }
  };
  
  // 新增
  const handleAdd = () => {
    dialogTitle.value = '新增预算配置';
    resetFormData();
    dialogVisible.value = true;
  };
  
  // 提交表单
  const handleSubmit = async () => {
    if (formRef.value) {
      formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 构建提交数据，确保类型与后端DTO匹配
            const submitData = {
              departmentId: Number(formData.departmentId),
              costItemId: Number(formData.costItemId),
              year: parseInt(formData.year),
              budgetAmount: new Number(formData.budgetAmount),
              remark: formData.remark
            };
            
            // 调用真实API
            let response;
            if (formData.id) {
              // 更新操作
              response = await budgetConfigApi.updateBudgetConfig(formData.id, submitData);
            } else {
              // 新增操作
              response = await budgetConfigApi.createBudgetConfig(submitData);
            }
            
            // 显示成功消息
            ElMessage.success(formData.id ? '预算配置更新成功' : '预算配置新增成功');
            
            // 关闭对话框
            dialogVisible.value = false;
            
            // 重置表单
            if (formRef.value) {
              formRef.value.resetFields();
            }
            resetFormData();
            
            // 重新加载数据
            getBudgetConfigs();
          } catch (error) {
            console.error('提交预算配置失败:', error);
            ElMessage.error('提交失败，请稍后重试');
          }
        }
      });
    }
  };
  
  // 删除
  const handleDelete = async (row) => {
    try {
      // 使用后端返回的名称或基于ID生成显示名称
      const departmentName = row.departmentName || row.department_name || `部门${row.departmentId || row.department_id}`;
      const costItemName = row.costItemName || row.cost_item_name || row.name || `未命名项目`;
      
      await ElMessageBox.confirm(
        `确定要删除「${departmentName} - ${costItemName}」的预算配置吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      await budgetConfigApi.deleteBudgetConfig(row.id);
      ElMessage.success('删除成功');
      // 刷新列表
      await getBudgetConfigs();
    } catch (error) {
      // 忽略取消操作错误
      if (error !== 'cancel') {
        console.error('删除预算配置失败:', error);
        ElMessage.error('删除失败，请稍后重试');
      }
    }
  };
  
  // 重置表单数据
  const resetFormData = () => {
    formData.id = '';
    formData.departmentId = '';
    formData.costItemId = '';
    formData.year = new Date().getFullYear().toString();
    formData.budgetAmount = null;
    formData.remark = '';
  };
  
  // 处理搜索
  const handleSearch = () => {
    pagination.currentPage = 1;
    getBudgetConfigs();
  };
  
  // 处理重置搜索
  const handleReset = () => {
    searchForm.year = new Date().getFullYear().toString();
    searchForm.departmentId = '';
    searchForm.costItemId = '';
    pagination.currentPage = 1;
    getBudgetConfigs();
  };
  
  // 处理分页变化
  const handlePageChange = (currentPage, pageSize) => {
    pagination.currentPage = currentPage;
    pagination.pageSize = pageSize;
    getBudgetConfigs();
  };
  
  // 初始化
  const init = () => {
    initYearOptions();
    initOptions();
    getBudgetConfigs();
  };
  
  return {
    // 状态
    loading,
    dialogVisible,
    dialogTitle,
    formRef,
    budgetConfigs,

    searchForm,
    pagination,
    formData,
    formRules,
    departmentOptions,
    costItemOptions,
    yearOptions,
    
    // 方法
    getBudgetConfigs,

    handleView,
    handleEdit,
    handleAdd,
    handleSubmit,
    handleDelete,
    resetFormData,
    handleSearch,
    handleReset,
    handlePageChange,
    init
  };
};

export default useBudgetConfig;